package model

import (
	"blogdemo/gin/errmsg"
	"github.com/jinzhu/gorm"
)

type Profile struct {
	gorm.Model
	Username string `gorm:"type:varchar(20); not null" json:"username"`
	Nickname string `gorm:"type:varchar(20); not null" json:"nickname"`
	Sex      string `gorm:"type:varchar(20)" json:"sex"`
	Desc     string `gorm:"type:varchar(200)" json:"desc"`
	Photo    string `gorm:"type:varchar(200)" json:"photo"`
}

// InitProfile 初始化个人资料
func InitProfile(theProfile *Profile) int {
	err := db.Create(&theProfile).Error
	if err != nil {
		return errmsg.FAIL
	}
	return errmsg.SUCCESS
}

// GetProfile 获取个人资料
func GetProfile(username string) (Profile, bool) {
	var profile Profile
	db.Where("username = ?", username).First(&profile)
	if profile.Username == "" {
		return profile, false
	}
	return profile, true
}

// CheckNickname 检查昵称是否为空
func CheckNickname(nickname string) bool {
	if len(nickname) == 0 {
		return false
	} else {
		for i := 0; i < len(nickname); i++ {
			if nickname[i] != ' ' {
				return true
			}
		}
	}
	return false
}

// ChangeProfile 更新数据库中的profile
func ChangeProfile(profile *Profile) int {
	err = db.Model(&profile).Where("username = ?", profile.Username).Updates(&profile).Error
	if err != nil {
		return errmsg.FAIL
	}
	return errmsg.SUCCESS
}
